package com.cn.onetrip.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.webkit.WebView.FindListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.onetrip.activity.R;
import com.cn.onetrip.objects.ArticleListObj;
import com.cn.onetrip.objects.RouteItemObj;
import com.cn.onetrip.objects.RoutePointObj;
import com.cn.onetrip.untility.DebugUtil;
import com.cn.onetrip.untility.SyncImageLoader;
import com.cn.onetrip.untility.SyncImageLoader.OnImageLoadListener;
import com.cn.onetrip.untility.SysApplication;

public class RouteItemAdapter extends BaseAdapter {

	public Vector<RouteItemObj> mModels = new Vector<RouteItemObj>();
	public Vector<ArticleListObj> Models = new Vector<ArticleListObj>();
	private LayoutInflater mInflater;
	private Context mContext;
	private ListView mListView;
	private Handler mhandler;
	private int TypeCount = 0;
	private boolean isFirstOutLine = true;
	private int firstOutLineIndex = -1;
	private SyncImageLoader syncImageLoader;
	private List<ImageView> imageViewsList = new ArrayList<ImageView>();

	public static boolean isRefresh = false;
	public static boolean isVisiable = true;
	public static boolean isMapping = false;

	public RouteItemAdapter(Context context, ListView listView, Handler handler) {
		mInflater = LayoutInflater.from(context);
		listView.setOnScrollListener(onScrollListener);
		syncImageLoader = new SyncImageLoader(context);
		mContext = context;
		mListView = listView;
		mhandler = handler;
	}

	public void addRoutes(int draw_image, String title, boolean isMore,
			int count) {
		RouteItemObj model = new RouteItemObj();
		model.draw_image = draw_image;
		model.title = title;
		model.isFree = isMore;
		model.rank = count;
		mModels.add(model);
	}

	public void addRoute(String imageUrl, String title, String subTitle,
			String distance, String time, int type) {
		ArticleListObj model = new ArticleListObj();
		model.icon = imageUrl;
		model.title = title;
		model.description = subTitle;
		model.distance = distance;
		model.spendTime = time;
		model.type_cd = type;
		Models.add(model);
	}

	public void clean() {
		Models.clear();
	}

	public void threadQuit() {
		if (syncImageLoader != null) {
			syncImageLoader.threadQuit();
		}
	}

	public void clear() {
		for (int i = 0; i < imageViewsList.size(); i++) {
			ImageView imageView = imageViewsList.get(i);
			imageView.setBackgroundDrawable(null);
			System.gc();
		}
		imageViewsList.clear();
	}

	public void setTypeCount(int count) {
		this.TypeCount = count;
	}

	@Override
	public int getCount() {
		return Models.size();
	}

	@Override
	public Object getItem(int position) {
		if (position >= getCount()) {
			return null;
		}
		return Models.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ArticleListObj model = Models.get(position);

		ImageView num = null;
		final ImageView image;
		ImageView lineTop, lineBottom;
		TextView text = null, itemDistance, itemTitle, itemRank, itemTime;
		RelativeLayout layoutTextBox;
		RelativeLayout leftLayout, topLayout, splitTop, split;
		ImageView rightBox;

		// final ViewHolder viewHolder;
		// if (convertView == null) {
		convertView = mInflater.inflate(R.layout.route_list_items, null);

		Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.alpha);
		Animation anim_long = AnimationUtils.loadAnimation(mContext,
				R.anim.alpha_long);
		Animation animRight = AnimationUtils.loadAnimation(mContext,
				R.anim.translation_right);
		Animation animRight2 = AnimationUtils.loadAnimation(mContext,
				R.anim.translation_right2);
		animRight2.setFillAfter(true);

		// viewHolder = new ViewHolder();

		layoutTextBox = (RelativeLayout) convertView
				.findViewById(R.id.rightRelativeLayout);
		leftLayout = (RelativeLayout) convertView
				.findViewById(R.id.leftRelativeLayout);
		num = (ImageView) convertView.findViewById(R.id.routeItemNum);
		lineTop = (ImageView) convertView.findViewById(R.id.itemLineTop);
		lineBottom = (ImageView) convertView.findViewById(R.id.itemLineBottom);
		image = (ImageView) convertView.findViewById(R.id.routeItemImage);
		topLayout = (RelativeLayout) convertView.findViewById(R.id.top_split);
		splitTop = (RelativeLayout) convertView
				.findViewById(R.id.item_top_layout);
		split = (RelativeLayout) convertView
				.findViewById(R.id.item_split_layout);
		itemDistance = (TextView) convertView
				.findViewById(R.id.routeItemDistance);
		itemTitle = (TextView) convertView.findViewById(R.id.routeItemTitle);
		itemRank = (TextView) convertView.findViewById(R.id.routeItemInfo);
		itemTime = (TextView) convertView.findViewById(R.id.routeItemTime);
		rightBox = (ImageView) convertView.findViewById(R.id.rightBox);

		// convertView.setTag(viewHolder);
		// } else {
		// viewHolder = (ViewHolder) convertView.getTag();
		// }

		syncImageLoader.loadImage(model.icon, new OnImageLoadListener() {

			@Override
			public void onImageLoad(Drawable drawable) {
				if (drawable != null) {
					image.setBackgroundDrawable(drawable);
				}
			}

			@Override
			public void onImageLoad(Integer t, Drawable drawable) {

			}

			@Override
			public void onError() {
			}

			@Override
			public void onError(Integer t) {

			}
		});

		if (position == 0) {
			topLayout.setVisibility(View.VISIBLE);
			splitTop.setVisibility(View.VISIBLE);
		} else {
			topLayout.setVisibility(View.GONE);
			splitTop.setVisibility(View.GONE);
		}
		split.setVisibility(View.GONE);
		lineTop.setVisibility(View.VISIBLE);
		lineBottom.setVisibility(View.VISIBLE);
		itemDistance.setVisibility(View.VISIBLE);

		RotateAnimation animation = new RotateAnimation(0, 90,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		animation.setDuration(0);
		animation.setFillAfter(true);
		itemDistance.startAnimation(animation);

		if (model.type_cd == RoutePointObj.TYPE_OUT_LINE) {
			int drawableIDNum = convertView.getResources().getIdentifier(
					"num_other_" + (position + 1), "drawable",
					mContext.getPackageName());
			num.setBackgroundResource(drawableIDNum);
			rightBox.setBackgroundResource(R.drawable.text_box_other);
			lineTop.setVisibility(View.GONE);
			lineBottom.setVisibility(View.GONE);
			itemDistance.setVisibility(View.GONE);

			if (isFirstOutLine) {
				firstOutLineIndex = position;
				isFirstOutLine = false;
			}

			if (position == firstOutLineIndex) {
				topLayout.setVisibility(View.VISIBLE);
				split.setVisibility(View.VISIBLE);
			} else {
				topLayout.setVisibility(View.GONE);
				split.setVisibility(View.GONE);
			}
		} else {
			int drawableIDNum = convertView.getResources().getIdentifier(
					"num_" + (position + 1), "drawable",
					mContext.getPackageName());
			num.setBackgroundResource(drawableIDNum);

			int drawableIDTextBox = convertView.getResources().getIdentifier(
					"text_box_"
							+ ((position + 1) % (SysApplication.POP_NUM / 2)),
					"drawable", mContext.getPackageName());
			rightBox.setBackgroundResource(drawableIDTextBox);
		}

		if (model.type_cd == RoutePointObj.TYPE_IN_LINE
				&& !model.distance.equals("") && model.distance != null
				&& !model.distance.equals("0.0")) {
			int index = (position + 1) % (SysApplication.POP_NUM / 2);
			// int drawableIDLine = convertView.getResources().getIdentifier(
			// "line_" + index, "drawable", mContext.getPackageName());

			int colorId = convertView.getResources().getIdentifier(
					"title_" + index + "_color", "color",
					mContext.getPackageName());
			itemDistance.setTextColor(convertView.getResources().getColor(
					colorId));

			lineTop.setBackgroundColor(convertView.getResources().getColor(
					colorId));
			int nextColorId = convertView.getResources().getIdentifier(
					"title_" + (index + 1) + "_color", "color",
					mContext.getPackageName());

			lineBottom.setBackgroundColor(convertView.getResources().getColor(
					nextColorId));

			itemDistance.setText(model.distance);
		} else {
			itemDistance.setVisibility(View.GONE);
			lineTop.setVisibility(View.GONE);
			lineBottom.setVisibility(View.GONE);
		}

		itemTitle.setText(model.title);
		itemRank.setText(model.description);
		if (model.spendTime == null || model.spendTime.equals("")) {
			itemTime.setVisibility(View.INVISIBLE);
		} else {
			itemTime.setText(mContext.getResources().getString(
					R.string.route_spend_time)
					+ model.spendTime);
		}

		if (isVisiable) {
			image.setVisibility(View.VISIBLE);
			leftLayout.setVisibility(View.VISIBLE);
		} else {
			image.setVisibility(View.INVISIBLE);
			leftLayout.setVisibility(View.INVISIBLE);
			layoutTextBox.startAnimation(animRight2);
		}

		if (!isRefresh) {
			leftLayout.startAnimation(anim);
			if (isVisiable) {
				layoutTextBox.startAnimation(animRight);
				image.startAnimation(anim);
			}
		}

		Message msg = Message.obtain();
		msg.what = 3;
		msg.arg1 = position;
		mhandler.sendMessage(msg);

		return convertView;
	}

	public static Bitmap drawableToBitmap(Drawable drawable, int viewWidth,
			int viewHeight) {

		if (((BitmapDrawable) drawable).getBitmap() == null) {
			Log.d("Bitmap", "Bitmap = null");
			return null;
		}
		int imgWidth = ((BitmapDrawable) drawable).getBitmap().getWidth();
		int imgHeight = ((BitmapDrawable) drawable).getBitmap().getHeight();

		// Log.i("View size:", viewWidth+","+viewHeight);
		int x, y, w, h;
		if (imgWidth * viewHeight > viewWidth * imgHeight) {
			h = (int) imgHeight;
			w = (int) (imgHeight * viewWidth / viewHeight);
			y = 0;
			x = (imgWidth - w) / 2;
		} else {
			w = (int) imgWidth;
			h = (int) (imgWidth * viewHeight / viewWidth);
			y = (imgHeight - h) / 2;
			x = 0;
		}
		Bitmap.Config config = Bitmap.Config.RGB_565;
		Bitmap bitmap = Bitmap.createBitmap(
				((BitmapDrawable) drawable).getBitmap(), x, y, w, h);
		return bitmap;
	}

	public void loadImage() {
		int start = mListView.getFirstVisiblePosition();
		int end = mListView.getLastVisiblePosition();

		if (end >= getCount()) {
			end = getCount() - 1;
		}
		syncImageLoader.setLoadLimit(start, end);
		syncImageLoader.unlock();
	}

	AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
				DebugUtil.debug("SCROLL_STATE_FLING");
				syncImageLoader.lock();
				break;
			case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
				DebugUtil.debug("SCROLL_STATE_IDLE");
				loadImage();
				break;
			case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				syncImageLoader.lock();
				break;

			default:
				break;
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
		}
	};

	public class ViewHolder {
		ImageView num;
		ImageView lineTop;
		ImageView lineBottom;
		ImageView image;
		// ImageView split;
		RelativeLayout topLayout;
		RelativeLayout split;
		RelativeLayout splitTop;

		TextView itemDistance;
		TextView itemTitle;
		TextView itemRank;
		TextView itemTime;

		RelativeLayout layoutTextBox;
	}
}
